/**
 * Conversation Manager - 对话管理系统
 * 基于 AI Writer Lite 的实现，为 IntelliMark 提供写作指导和对话历史管理
 */

import Store from 'electron-store'
import { v4 as uuidv4 } from 'uuid'
import { BaseMessage, HumanMessage, AIMessage, SystemMessage } from '@langchain/core/messages'

export interface ConversationMessage {
  id: string
  role: 'user' | 'assistant' | 'system'
  content: string
  timestamp: number
  metadata?: {
    model?: string
    provider?: string
    tokensUsed?: number
    cost?: number
    context?: string
    operation?: string
  }
}

export interface ConversationSession {
  id: string
  documentId?: string
  title: string
  messages: ConversationMessage[]
  createdAt: number
  updatedAt: number
  metadata: {
    model?: string
    provider?: string
    totalTokens: number
    totalCost: number
    messageCount: number
  }
}

export interface ConversationSettings {
  maxMessagesPerSession: number
  compressionThreshold: number
  autoSave: boolean
  enableContextMemory: boolean
  maxHistoryLength: number
}

export class ConversationManager {
  private store: Store
  private settings: ConversationSettings

  constructor() {
    this.store = new Store({
      name: 'conversation-history',
      defaults: {
        sessions: {},
        globalContext: '',
        settings: {
          maxMessagesPerSession: 50,
          compressionThreshold: 30,
          autoSave: true,
          enableContextMemory: true,
          maxHistoryLength: 100
        }
      }
    })

    this.settings = this.store.get('settings') as ConversationSettings
  }

  /**
   * 创建新的对话会话
   */
  public createSession(documentId?: string, title?: string): string {
    const sessionId = uuidv4()
    const now = Date.now()

    const session: ConversationSession = {
      id: sessionId,
      documentId,
      title: title || `对话 ${new Date(now).toLocaleString()}`,
      messages: [],
      createdAt: now,
      updatedAt: now,
      metadata: {
        totalTokens: 0,
        totalCost: 0,
        messageCount: 0
      }
    }

    this.store.set(`sessions.${sessionId}`, session)
    console.log(`Created conversation session ${sessionId} for document ${documentId}`)
    return sessionId
  }

  /**
   * 添加消息到对话会话
   */
  public addMessage(
    sessionId: string,
    role: 'user' | 'assistant' | 'system',
    content: string,
    metadata?: {
      model?: string
      provider?: string
      tokensUsed?: number
      cost?: number
      context?: string
      operation?: string
    }
  ): string {
    const session = this.getSession(sessionId)
    if (!session) {
      throw new Error(`Session ${sessionId} not found`)
    }

    const messageId = uuidv4()
    const now = Date.now()

    const message: ConversationMessage = {
      id: messageId,
      role,
      content,
      timestamp: now,
      metadata
    }

    session.messages.push(message)
    session.updatedAt = now
    session.metadata.messageCount = session.messages.length

    // 更新元数据
    if (metadata?.tokensUsed) {
      session.metadata.totalTokens += metadata.tokensUsed
    }
    if (metadata?.cost) {
      session.metadata.totalCost += metadata.cost
    }
    if (metadata?.model) {
      session.metadata.model = metadata.model
    }
    if (metadata?.provider) {
      session.metadata.provider = metadata.provider
    }

    // 检查是否需要压缩
    if (session.messages.length >= this.settings.compressionThreshold) {
      this.compressSession(session)
    }

    this.store.set(`sessions.${sessionId}`, session)
    console.log(`Added message to session ${sessionId}`)
    return messageId
  }

  /**
   * 获取对话会话
   */
  public getSession(sessionId: string): ConversationSession | null {
    return this.store.get(`sessions.${sessionId}`) as ConversationSession || null
  }

  /**
   * 获取文档的所有对话会话
   */
  public getDocumentSessions(documentId: string): ConversationSession[] {
    const sessions = this.store.get('sessions') as Record<string, ConversationSession>
    return Object.values(sessions).filter(session => session.documentId === documentId)
  }

  /**
   * 获取所有对话会话
   */
  public getAllSessions(): ConversationSession[] {
    const sessions = this.store.get('sessions') as Record<string, ConversationSession>
    return Object.values(sessions).sort((a, b) => b.updatedAt - a.updatedAt)
  }

  /**
   * 删除对话会话
   */
  public deleteSession(sessionId: string): boolean {
    const session = this.getSession(sessionId)
    if (!session) {
      return false
    }

    this.store.delete(`sessions.${sessionId}`)
    console.log(`Deleted session ${sessionId}`)
    return true
  }

  /**
   * 更新会话标题
   */
  public updateSessionTitle(sessionId: string, title: string): boolean {
    const session = this.getSession(sessionId)
    if (!session) {
      return false
    }

    session.title = title
    session.updatedAt = Date.now()
    this.store.set(`sessions.${sessionId}`, session)
    return true
  }

  /**
   * 获取最近的对话上下文
   */
  public getRecentContext(
    sessionId: string,
    maxMessages: number = 10
  ): {
    messages: ConversationMessage[]
    summary?: string
  } {
    const session = this.getSession(sessionId)
    if (!session) {
      return { messages: [] }
    }

    const recentMessages = session.messages.slice(-maxMessages)

    // 如果消息太多，提供摘要
    let summary: string | undefined
    if (session.messages.length > maxMessages) {
      summary = this.generateSessionSummary(session.messages.slice(0, -maxMessages))
    }

    return {
      messages: recentMessages,
      summary
    }
  }

  /**
   * 转换为 LangChain 消息格式
   */
  public toLangChainMessages(sessionId: string, includeSystemPrompt: boolean = false): BaseMessage[] {
    const context = this.getRecentContext(sessionId)
    const messages: BaseMessage[] = []

    // 添加系统提示
    if (includeSystemPrompt && context.summary) {
      messages.push(new SystemMessage(
        `以下是对话历史的摘要: ${context.summary}\n\n请基于这个上下文继续对话。`
      ))
    }

    // 转换消息格式
    context.messages.forEach(msg => {
      switch (msg.role) {
        case 'user':
          messages.push(new HumanMessage(msg.content))
          break
        case 'assistant':
          messages.push(new AIMessage(msg.content))
          break
        case 'system':
          messages.push(new SystemMessage(msg.content))
          break
      }
    })

    return messages
  }

  /**
   * 清理旧会话
   */
  public cleanupOldSessions(maxAge: number = 30 * 24 * 60 * 60 * 1000): void {
    const sessions = this.store.get('sessions') as Record<string, ConversationSession>
    const now = Date.now()
    const sessionsToDelete: string[] = []

    Object.entries(sessions).forEach(([sessionId, session]) => {
      if (now - session.updatedAt > maxAge) {
        sessionsToDelete.push(sessionId)
      }
    })

    sessionsToDelete.forEach(sessionId => {
      this.deleteSession(sessionId)
    })

    console.log(`Cleaned up ${sessionsToDelete.length} old sessions`)
  }

  /**
   * 压缩会话历史
   */
  public compressSession(session: ConversationSession): void {
    if (session.messages.length < this.settings.compressionThreshold) {
      return
    }

    // 保留最近的几条消息
    const keepCount = Math.floor(this.settings.compressionThreshold / 2)
    const recentMessages = session.messages.slice(-keepCount)

    // 生成旧消息的摘要
    const oldMessages = session.messages.slice(0, -keepCount)
    const summary = this.generateSessionSummary(oldMessages)

    // 创建摘要消息
    if (summary) {
      const summaryMessage: ConversationMessage = {
        id: uuidv4(),
        role: 'system',
        content: `对话历史摘要: ${summary}`,
        timestamp: Date.now(),
        metadata: {
          operation: 'compression'
        }
      }

      session.messages = [summaryMessage, ...recentMessages]
    } else {
      session.messages = recentMessages
    }

    console.log(`Compressed session ${session.id} from ${oldMessages.length + recentMessages.length} to ${session.messages.length} messages`)
  }

  /**
   * 生成会话摘要
   */
  private generateSessionSummary(messages: ConversationMessage[]): string {
    if (messages.length === 0) {
      return ''
    }

    const userMessages = messages.filter(msg => msg.role === 'user')
    const assistantMessages = messages.filter(msg => msg.role === 'assistant')

    const topics: string[] = []
    const operations: string[] = []

    // 提取用户主要话题
    userMessages.slice(-5).forEach(msg => {
      const content = msg.content.substring(0, 100) // 取前100个字符
      if (content.includes('润色') || content.includes('polish')) {
        operations.push('文本润色')
      } else if (content.includes('扩写') || content.includes('expand')) {
        operations.push('文本扩写')
      } else if (content.includes('翻译') || content.includes('translate')) {
        operations.push('文本翻译')
      } else if (content.includes('续写') || content.includes('continue')) {
        operations.push('续写内容')
      }
    })

    const summaryParts: string[] = []

    if (operations.length > 0) {
      summaryParts.push(`主要操作: ${operations.join(', ')}`)
    }

    summaryParts.push(`对话轮数: ${userMessages.length}`)
    summaryParts.push(`最后活动: ${new Date(messages[messages.length - 1].timestamp).toLocaleString()}`)

    return summaryParts.join('; ')
  }

  /**
   * 获取全局上下文
   */
  public getGlobalContext(): string {
    return this.store.get('globalContext', '') as string
  }

  /**
   * 设置全局上下文
   */
  public setGlobalContext(context: string): void {
    this.store.set('globalContext', context)
  }

  /**
   * 获取统计信息
   */
  public getStatistics(): {
    totalSessions: number
    totalMessages: number
    totalTokens: number
    totalCost: number
    averageMessagesPerSession: number
    oldestSession?: Date
    newestSession?: Date
  } {
    const sessions = this.getAllSessions()

    let totalMessages = 0
    let totalTokens = 0
    let totalCost = 0
    let oldestTimestamp = Date.now()
    let newestTimestamp = 0

    sessions.forEach(session => {
      totalMessages += session.messages.length
      totalTokens += session.metadata.totalTokens
      totalCost += session.metadata.totalCost
      oldestTimestamp = Math.min(oldestTimestamp, session.createdAt)
      newestTimestamp = Math.max(newestTimestamp, session.updatedAt)
    })

    return {
      totalSessions: sessions.length,
      totalMessages,
      totalTokens,
      totalCost,
      averageMessagesPerSession: sessions.length > 0 ? totalMessages / sessions.length : 0,
      oldestSession: sessions.length > 0 ? new Date(oldestTimestamp) : undefined,
      newestSession: sessions.length > 0 ? new Date(newestTimestamp) : undefined
    }
  }

  /**
   * 导出会话
   */
  public exportSession(sessionId: string): ConversationSession | null {
    return this.getSession(sessionId)
  }

  /**
   * 导入会话
   */
  public importSession(session: ConversationSession): void {
    this.store.set(`sessions.${session.id}`, session)
    console.log(`Imported session ${session.id}`)
  }

  /**
   * 更新设置
   */
  public updateSettings(newSettings: Partial<ConversationSettings>): void {
    this.settings = { ...this.settings, ...newSettings }
    this.store.set('settings', this.settings)
  }

  /**
   * 获取设置
   */
  public getSettings(): ConversationSettings {
    return { ...this.settings }
  }

  /**
   * 清空所有数据
   */
  public clearAllData(): void {
    this.store.clear()
    console.log('Cleared all conversation data')
  }
}

// 导出单例实例
let conversationManagerInstance: ConversationManager | null = null

export function getConversationManager(): ConversationManager {
  if (!conversationManagerInstance) {
    conversationManagerInstance = new ConversationManager()
  }
  return conversationManagerInstance
}